'use strict'

const Controller = require('egg').Controller
const nodemailer = require('nodemailer')

const path = require('path')
class HomeController extends Controller {
  async index() {
    const { ctx } = this
    ctx.body = 'hi, egg'
  }

  async getTest() {
    const { ctx, app } = this

    ctx.body = {
      body: ctx.query,
    }
  }

  async postTest() {
    const { ctx, app } = this

    ctx.body = {
      body: ctx.request.body,
    }
  }

  // oss 负责跟阿里云oss联系
  async upload() {
    const { ctx, app } = this
    // 1. 获取到前端传递过来的file文件
    const file = this.ctx.request.files[0]
    let filename = path.join(`day13/${Date.now()}_`, file.filename)
    const result = await ctx.oss.put(filename, file.filepath)
    ctx.body = { url: result.url }
  }

  async multipartUpload() {
    const { ctx, app } = this
    const progress = (p, _checkpoint) => {
      // Object的上传进度。
      console.log(p)
      // 分片上传的断点信息。
      console.log(_checkpoint)
    }
    try {
      const file = this.ctx.request.files[0]
      let filename = path.join(`day13/${Date.now()}_`, file.filename)
      // 依次填写Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。Object完整路径中不能包含Bucket名称。
      // 如果本地文件的完整路径中未指定本地路径（例如examplefile.txt），则默认从示例程序所属项目对应本地路径中上传文件。
      const result = await ctx.oss.multipartUpload(filename, file.filepath, {
        progress,
        // headers,
        // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
        meta: {
          year: 2020,
          people: 'test',
        },
      })
      console.log(result)
      // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
      // const head = await client.head(filename)
      // console.log(head)
      this.ctx.body = result
    } catch (e) {
      // 捕获超时异常。
      if (e.code === 'ConnectionTimeoutError') {
        console.log('TimeoutError')
        this.ctx.body = 'TimeoutError'
        // do ConnectionTimeoutError operation
      }
      console.log(e)
      this.ctx.body = e
    }
  }

  async getImage() {
    try {
      const { ctx, app } = this
      const { filename } = ctx.request.body
      // 1. 获取到前端传递过来的file文件

      // const file = this.ctx.request.files[0]
      // let filename = path.join(`day13/${Date.now()}_`, file.filename)
      // 填写Object完整路径和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
      // 如果指定的本地文件存在会覆盖，不存在则新建。
      // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。

      let result = await ctx.oss.get(
        filename,
        path.join(__dirname, `../public/imgs/${filename}`)
      )
      // console.log(path.join(__dirname, '../public/imgs')
      ctx.body = result
    } catch (e) {
      console.log(e)
    }
  }

  // 图片删除
  async deleteFile() {
    // http://wyp0712.oss-cn-beijing.aliyuncs.com/egg-oss-demo/8jsqnyfm3x40000.jpeg
    try {
      const { ctx, app } = this
      const { filename } = ctx.request.body
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      let result = await this.ctx.oss.delete(filename)
      this.ctx.body = { result }
    } catch (e) {
      console.log(e)
      this.ctx.body = e
    }
  }

  async emailValidate() {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    let testAccount = await nodemailer.createTestAccount()
    console.log('testAccount:', testAccount)
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: testAccount.user, // generated ethereal user
        pass: testAccount.pass, // generated ethereal password
      },
    })
    // send mail with defined transport object
    let info = await transporter.sendMail({
      from: '609432180@qq.com', // sender address
      to: '17610425238@163.com', // list of receivers
      subject: 'Hello ✔', // Subject line
      text: 'Hello world?', // plain text body
      html: '<h1>msg: 123</h1>', // html body
    })
    console.log('Message sent: %s', info.messageId)
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
    this.ctx.body = info
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
  }
}

module.exports = HomeController
